<template>
    <div class='head'>
        <div style="display: flex;justify-content: center; padding-top: 21%;" v-if="this.$store.state.WarehousingData.length == 0">
            <el-upload
                class="avatar-uploader"
                action=""
                :show-file-list="false"
                :http-request="handleRequest"
                accept=".xlsx"
            >
                <div>
                    <div style="display:flex; justify-content: center;">
                        <img src="../assets/unpad.png" alt="" />
                    </div>
                    <p style="font-weight: 400; font-size: 15px;color: #31373D; line-height: 14px; margin-top: 20px;">请将学员相关信息进行导入，<span style="color:#2F51FF;">点击上传</span></p>
                    <div style="display: flex;justify-content: center;align-items: center; margin-top: 20px;">
                        <el-button type="success" @click='flieexpor()' style='width: 200px; height: 41px; font-size: 20px;'>下载模板</el-button>
                    </div>
                </div>
            </el-upload>
        </div>
        <div v-else style="width: 100%; height: 95%;">
            <div style="display:flex; justify-content: space-between;">
                <div>
                    <el-button type="primary" @click="Return()">返回</el-button>
                </div>
                <div>
                    <el-select v-model="classDatavalue" placeholder="选择培训期" style="width: 240px">
                        <el-option
                            v-for="item in classData"
                            :key="item.c_id"
                            :label="item.c_name"
                            :value="item.c_id"
                            style="height: 31px; overflow: hidden;"
                        />
                    </el-select>
                    <el-button type="primary" @click="uploadData()">上传学员</el-button>
                </div>
            </div>
            <div class='table_content'>
                <el-table
                    height="100%"
                    :data="this.$store.state.Warehousing"
                    @selection-change="handleSelectionChange"
                    stripe
                    style="width: 100%">
                    <el-table-column
                        v-for="(item,index) in this.$store.state.studentData"
                        :prop="item.prop"
                        :label='item.name'
                        width="130">
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" >
                        <template #default="scope">
                            <el-button link type="primary" size="small" @click="deleteRow(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div style='display:flex; justify-content: center; padding-top: 10px;'>
                <el-pagination
                    background
                    @current-change="pagesChange"
                    layout="prev, pager, next"
                    :total="tableDataTwoLength">
                </el-pagination>
            </div>
        </div>
    </div>
</template>
<script>
import { read, utils } from 'xlsx';
import { setImportHistory } from '../utils/index';
export default {
   components: {},
    data() {
       return {
            tableDataTwoLength:10,
            delesplice:[],
            page:1,
            recordsData:[],
            studentData:[],
            classData:[],
            classDatavalue:'',
            headers:[],
       };
   },
//监听属性 类似于data概念
    computed: {},
//监控data中的数据变化
    watch: {},
    //生命周期 - 创建完成（可以访问当前this实例）
    created() {
        this.get('class/').then(res=>{
            this.classData = res.data
        })
    },
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {
    },
    //方法集合
    methods: {
        flieexpor() {
            // http://'+window.location.host+
            window.open('http://'+window.location.host+'/api/file/export_example', '_blank');
        },
        Return(){
            this.$store.state.WarehousingData = []
            this.$store.state.Warehousing = []
            this.$store.state.studentData = []
        },
        // 全部学员
        All_students() {
            this.get('/user/'+this.page+'?size=10&r_id=1').then(res=>{
                console.log(res)
            })
        },
        query() {

        },
        uploadData() {
            if(this.classDatavalue == ''){
                this.$message({
                    message: '请选择培训期',
                    type: 'error',
                })
                return
            }
            this.$store.state.Warehousing.forEach((item,index) =>{
                item['c_id'] = this.classDatavalue
            })
            this.$store.state.WarehousingData.forEach((item,index) =>{
                item['c_id'] = this.classDatavalue
            })
            this.post('/student/save/batch',this.$store.state.WarehousingData).then(res=>{
                if(res.code == 200){
                    this.$message({
                        message: '上传成功！',
                        type: 'success',
                    })
                    this.$store.state.Warehousing = []
                    this.$store.state.WarehousingData = []
                }else{
                    this.$message({
                        message: res.data,
                        type: 'error',
                    })
                    this.$store.state.Warehousing = []
                    this.$store.state.WarehousingData = []
                }
            })
        },
        pagesChange(val){
            this.page = val
            this.$store.state.Warehousing = []
            for(let i=Number(val+'0'-10); i<Number(val+'0'); i++){
                this.$store.state.Warehousing.push(this.$store.state.WarehousingData[i])
            }
            for(let i=this.$store.state.Warehousing.length-1; i>=0;  i--) {
                if(this.$store.state.Warehousing[i] == undefined){
                    this.$store.state.Warehousing.splice(i,1)
                }
            }
            console.log(  this.$store.state.Warehousing  )
        },
        deleteRow(item){
            this.$store.state.Warehousing.forEach((val,INX) =>{
                if(item['警号'] == val['警号']){
                    this.$store.state.Warehousing.splice(INX,1)
                }
            })
            console.log( this.$store.state.Warehousing )
        },
        handleSelectionChange (val) {
            this.delesplice = val
        },
        handleAvatarSuccess(UploadProps){

        },
        beforeAvatarUpload(rawFile) {
            return true
        },
        handleRequest (fileData) {
            this.$store.state.WarehousingData = []
            this.$store.state.Warehousing = []
            this.$store.state.studentData = []
            setImportHistory({ file: fileData.file.name});
            this.readXLSX(fileData.file) .then((res) => {
                this.tableDataTwoLength = res.length
                let A = this.headers.filter((item)=>{
                    return item != ''
                })
                A.forEach((item) =>{
                    this.$store.state.studentData.push({
                        name:item,
                        prop:item
                    })
                })
                this.$store.state.WarehousingData = res
                for(let i=0; i<res.length; i++){
                    if(i<=9){
                        this.$store.state.Warehousing.push(res[i])
                    }
                }
            }).catch((err) => {

            });
        },
        readXLSX (file) {
            let nameSplit = file.name.split('.');
            let format = nameSplit[nameSplit.length - 1];
            if (!['xlsx', 'csv'].includes(format)) {
                return false;
            }
            let _this = this
            return new Promise((resolve, reject) => {
                let reader = new FileReader();
                reader.readAsBinaryString(file);
                reader.onload = function (evt) {
                    let data = evt.target.result;
                    try {
                        var workbook = read(data, { type: 'binary' });
                        const wsname = workbook.SheetNames[0];
                        const ws = utils.sheet_to_json(workbook.Sheets[wsname]); 

                        let firstWorkSheet = workbook.Sheets[workbook.SheetNames[0]];

                        _this.headers = []
                        const range = utils.decode_range(firstWorkSheet["!ref"]);
                        let C;
                        const R = range.s.r;
                        for (C = range.s.c; C <= range.e.c; ++C) {
                            const cell = firstWorkSheet[utils.encode_cell({ c: C, r: R })];
                            let hdr = "" 
                            if (cell && cell.t) hdr = utils.format_cell(cell);
                            _this.headers.push(hdr);
                        }
                        resolve(ws);
                    } catch (err) {
                        reject('some wrong with import');
                    }
                };
            });
        },
    },
    //生命周期 - 创建之前 
    beforeCreate() {},
    //生命周期 - 挂载之前
    beforeMount() {},
    // 生命周期 - 更新之前 
    beforeUpdate() {},
    //生命周期 - 更新之后
    updated() {},
    //生命周期 - 销毁之前
    beforeDestroy() {},
    //生命周期 - 销毁完成
    destroyed() {},
    //如果页面有keep-alive缓存功能，这个函数会触发
    activated() {},
}
</script>
<style  scoped>
.table_content{
    width:100%; 
    height: 94%; 
    overflow: auto;
}
.table_content::-webkit-scrollbar {
    width: 0;
} 
.el-icon.avatar-uploader-icon{
    box-shadow: 4px 5px 63px -24px rgba(0, 0, 0, 0.5);
}
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}
.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
.head{
    width: 100%;
    height: 90%;
    overflow: auto;
}
</style>